/**
 *  Copyright 2010 ShenYang voole Co. Ltd.
 *  All right reserved. 
 */
package com.dianning.service.template;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import com.dianning.bean.Channel;
import com.dianning.service.ChannelService;
import com.dianning.service.InfoService;

import freemarker.template.Template;

/**
 * 功能描述:模版生成功具
 *
 * 创建日期 May 4, 2010
 *
 * @author zhangbaochao
 *
 * @version 1.0
 *
 */
public class TemplateUtil {
	private static final Log logger = LogFactory.getLog(TemplateUtil.class);
	private static final String SPLITTER = ","; // 转换的字符
	private FreeMarkerConfigurer freeMarkerConfigurer;
	private ChannelService channelService;
	private InfoService infoService;
	
	
	public FreeMarkerConfigurer getFreeMarkerConfigurer() {
		return freeMarkerConfigurer;
	}

	public void setFreeMarkerConfigurer(FreeMarkerConfigurer freeMarkerConfigurer) {
		this.freeMarkerConfigurer = freeMarkerConfigurer;
	}

	public ChannelService getChannelService() {
		return channelService;
	}

	public void setChannelService(ChannelService channelService) {
		this.channelService = channelService;
	}
	
	public InfoService getInfoService() {
		return infoService;
	}

	public void setInfoService(InfoService infoService) {
		this.infoService = infoService;
	}


	/**
	 * @param input
	 * 			模版内容
	 * @return Map		
	 * @throws Exception
	 */
	public Map getIndexPage(String input) throws Exception{
		try {
			Map map=new HashMap();
			//显示记数
			String regex = "<!--\\{(.*?)\\}-->";
			Pattern p = Pattern.compile(regex);
		    Matcher m = p.matcher(input);
		    while (m.find()) {
		    	String[] args = StringUtils.split(m.group(1), SPLITTER);
		    	String code = args[0];
		    	Channel c = this.getChannelService().findChannelByCode(code);
		    	if(c!=null){
		    		long num = this.getInfoService().getInfoNumByCid(c.getId(), 1);
		    		 map.put(args[0],num);
		    	}
		    }
		    return map;
		} catch (Exception ex) {
			logger.error(ex);
			throw new Exception(ex);
		}
	}
}
